package aspiration;

import gestionSites.Page;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

/**
 * classe de t�l�chargement de page web
 *
 */
public class PageDownloader extends Downloader {

	/**
	 * liste de balises html
	 */
	private ArrayList<String> htmlList;

	/**
	 * constructeur
	 * @param _url url � t�l�charger
	 * @param _target destination du t�l�chargement
	 * @param _src site web source
	 * @param _htmlList liste de balises
	 */
	public PageDownloader(String _url, String _target, String _src, ArrayList<String> _htmlList) {
		
		super(_target, _src);
		try {
			
			url = new URL(_url);
		} catch (MalformedURLException e) {
			System.out.println("Malformed url : "+this.url);
		}
		htmlList = _htmlList;
	}
	
	/**
	 * cr�ation du dossier racine
	 * @param src
	 */
	private void creerDossierRacine(String src) {
		String racine = src.substring(7, src.length());
		File dossier = new File(target+"/"+racine);
		dossier.mkdirs();
	}
	
	/**
	 * sauvegarde de la page
	 * @param page
	 */
	public void save(Page page) {
		
		creerDossierRacine(src);
		
		String surl = appendDotHtml(toRelative(url.toString()));
	
		if (surl.contains("/.html"))
			return;
		
		String racine = src.substring(7, src.length());
		
		if (surl.contains("/")) {
			
			String reps = surl.substring(0, surl.lastIndexOf("/"));
			File dossiers = new File(target+"/"+racine+"/"+reps+"/");
			dossiers.mkdirs();
		}
		

		surl = surl.replaceAll("\"|\\*|\\?|<|>|\\|", "-");

		
		File fichier = new File(target+"/"+racine+"/"+surl);
		
		page.setTaillePage(fichier.length());
		SiteCapturer.accumulatedSize+=fichier.length();
		PrintWriter pw;
		
		try {
			
			pw = new PrintWriter(new FileOutputStream(fichier));
			
			for (int i=0; i<htmlList.size(); i++)
				pw.print(htmlList.get(i));
			
			
			pw.close();
			
		} catch (FileNotFoundException e) {
			System.out.println("File not found : "+fichier.getName());
		}
	}

	@Override
	public void save() {
				
	}
}
